{% extends 'inventory/base.html' %}

{% block title %}销售管理 - {{ block.super }}{% endblock %}

{% block content %}
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3">
                    <div>
                        <h2 class="card-title mb-0">销售记录</h2>
                        <p class="text-muted mb-md-0">管理所有销售交易信息</p>
                    </div>
                    <div class="d-flex flex-wrap gap-2">
                        <a href="{% url 'sale_create' %}" class="btn btn-primary">
                            <i class="bi bi-cart-plus me-1"></i> 新增销售
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <div class="row mb-3">
                    <div class="col-lg-8 mb-3 mb-lg-0">
                        <div class="d-flex flex-column flex-md-row gap-2">
                            <div class="input-group">
                                <span class="input-group-text bg-primary text-white"><i class="bi bi-search"></i></span>
                                <input type="text" class="form-control border-primary" id="searchInput" placeholder="搜索订单编号或客户...">
                                <button class="btn btn-outline-primary d-none d-md-inline-block" type="button" id="clearSearch" title="清除搜索"><i class="bi bi-x-lg"></i></button>
                            </div>
                            <div class="input-group">
                                <span class="input-group-text bg-primary text-white"><i class="bi bi-calendar3"></i></span>
                                <input type="date" class="form-control border-primary" id="dateFilter" placeholder="按日期筛选">
                                <button class="btn btn-outline-primary" type="button" id="clearDate" title="清除日期"><i class="bi bi-x-lg"></i></button>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-4 d-flex justify-content-lg-end align-items-center">
                        <div class="btn-group">
                            <button type="button" class="btn btn-outline-secondary active" id="viewAll">全部</button>
                            <button type="button" class="btn btn-outline-secondary" id="viewToday">今日</button>
                            <button type="button" class="btn btn-outline-secondary" id="viewMonth">本月</button>
                        </div>
                    </div>
                </div>
                
                <div class="table-responsive table-container">
                    <table class="table table-striped table-hover align-middle">
                        <thead>
                            <tr>
                                <th>订单信息</th>
                                <th>销售日期</th>
                                <th>客户</th>
                                <th>金额</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for sale in sales %}
                            <tr class="sale-row" data-date="{{ sale.created_at|date:'Y-m-d' }}">
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="me-3">
                                            <div class="bg-primary text-white rounded d-flex align-items-center justify-content-center" style="width: 40px; height: 40px">
                                                <i class="bi bi-receipt"></i>
                                            </div>
                                        </div>
                                        <div>
                                            <h6 class="mb-0">订单 #{{ sale.id }}</h6>
                                            <small class="text-muted">{{ sale.total_quantity }} 件商品</small>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <div>
                                        <span>{{ sale.created_at|date:"Y-m-d" }}</span><br>
                                        <small class="text-muted">{{ sale.created_at|date:"H:i" }}</small>
                                    </div>
                                </td>
                                <td>
                                    {% if sale.member %}
                                    <span class="badge bg-info text-dark">{{ sale.member.name }}</span>
                                    {% else %}
                                    <span class="text-muted">散客</span>
                                    {% endif %}
                                </td>
                                <td>
                                    <span class="fw-bold text-success">¥{{ sale.total_amount }}</span>
                                    {% if sale.discount_amount %}
                                    <br><small class="text-muted">优惠: ¥{{ sale.discount_amount }}</small>
                                    {% endif %}
                                </td>
                                <td>
                                    <span class="badge bg-success">已完成</span>
                                </td>
                                <td>
                                    <div class="btn-group">
                                        <a href="{% url 'sale_detail' sale.id %}" class="btn btn-sm btn-outline-info" title="查看详情">
                                            <i class="bi bi-eye"></i>
                                        </a>
                                        <a href="#" class="btn btn-sm btn-outline-secondary" title="打印">
                                            <i class="bi bi-printer"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            {% empty %}
                            <tr>
                                <td colspan="6" class="text-center py-4">
                                    <div class="d-flex flex-column align-items-center">
                                        <i class="bi bi-cart-x text-muted" style="font-size: 2rem;"></i>
                                        <p class="mt-2 mb-0">暂无销售记录</p>
                                        <small class="text-muted">点击"新增销售"按钮创建销售记录</small>
                                    </div>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
                
                <!-- 销售统计 -->
                {% if sales %}
                <div class="row mt-4">
                    <div class="col-md-4 mb-3 mb-md-0">
                        <div class="card border-0 bg-gradient-light h-100 shadow-sm">
                            <div class="card-body p-4">
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <h6 class="card-subtitle text-muted">今日销售额</h6>
                                    <div class="stat-icon bg-success-subtle rounded-circle p-2">
                                        <i class="bi bi-currency-yen text-success fs-4"></i>
                                    </div>
                                </div>
                                <h3 class="mb-0 text-success fw-bold">¥{{ today_sales|floatformat:2|default:"0.00" }}</h3>
                                <div class="progress mt-3" style="height: 4px;">
                                    <div class="progress-bar bg-success" role="progressbar" style="width: 75%" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-3 mb-md-0">
                        <div class="card border-0 bg-gradient-light h-100 shadow-sm">
                            <div class="card-body p-4">
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <h6 class="card-subtitle text-muted">本月销售额</h6>
                                    <div class="stat-icon bg-primary-subtle rounded-circle p-2">
                                        <i class="bi bi-bar-chart-line text-primary fs-4"></i>
                                    </div>
                                </div>
                                <h3 class="mb-0 text-primary fw-bold">¥{{ month_sales|floatformat:2|default:"0.00" }}</h3>
                                <div class="progress mt-3" style="height: 4px;">
                                    <div class="progress-bar bg-primary" role="progressbar" style="width: 65%" aria-valuenow="65" aria-valuemin="0" aria-valuemax="100"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card border-0 bg-gradient-light h-100 shadow-sm">
                            <div class="card-body p-4">
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <h6 class="card-subtitle text-muted">总订单数</h6>
                                    <div class="stat-icon bg-info-subtle rounded-circle p-2">
                                        <i class="bi bi-receipt text-info fs-4"></i>
                                    </div>
                                </div>
                                <h3 class="mb-0 text-info fw-bold">{{ total_sales }}</h3>
                                <div class="progress mt-3" style="height: 4px;">
                                    <div class="progress-bar bg-info" role="progressbar" style="width: 85%" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                {% endif %}
                
                <!-- 分页控件 -->
                {% if sales %}
                <div class="d-flex justify-content-between align-items-center mt-4">
                    <div class="text-muted small">
                        显示 1 至 {{ sales|length }} 条，共 {{ sales|length }} 条记录
                    </div>
                    <nav aria-label="Page navigation">
                        <ul class="pagination pagination-sm mb-0">
                            <li class="page-item disabled">
                                <a class="page-link" href="#" aria-label="Previous">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>
                            <li class="page-item active"><a class="page-link" href="#">1</a></li>
                            <li class="page-item disabled">
                                <a class="page-link" href="#" aria-label="Next">
                                    <span aria-hidden="true">&raquo;</span>
                                </a>
                            </li>
                        </ul>
                    </nav>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化工具提示
        const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl, {
                delay: { show: 300, hide: 100 }
            });
        });
        
        // 表格行悬停效果
        const saleRows = document.querySelectorAll('.sale-row');
        saleRows.forEach(row => {
            row.addEventListener('mouseenter', function() {
                this.style.backgroundColor = 'rgba(52, 152, 219, 0.05)';
                this.style.transition = 'background-color 0.3s ease';
                const icon = this.querySelector('.bg-primary');
                if (icon) {
                    icon.style.transform = 'scale(1.1)';
                }
            });
            
            row.addEventListener('mouseleave', function() {
                this.style.backgroundColor = '';
                const icon = this.querySelector('.bg-primary');
                if (icon) {
                    icon.style.transform = 'scale(1)';
                }
            });
        });
        
        // 搜索功能增强
        const searchInput = document.getElementById('searchInput');
        const clearSearch = document.getElementById('clearSearch');
        
        if (searchInput) {
            searchInput.addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase();
                filterTable();
                
                // 显示/隐藏清除按钮
                if (searchTerm.length > 0) {
                    clearSearch.classList.remove('d-none');
                } else {
                    clearSearch.classList.add('d-none');
                }
            });
            
            // 清除搜索
            if (clearSearch) {
                clearSearch.addEventListener('click', function() {
                    searchInput.value = '';
                    searchInput.focus();
                    this.classList.add('d-none');
                    filterTable();
                });
            }
        }
        
        // 日期筛选功能增强
        const dateFilter = document.getElementById('dateFilter');
        const clearDate = document.getElementById('clearDate');
        
        if (dateFilter) {
            dateFilter.addEventListener('change', function() {
                filterTable();
            });
            
            // 清除日期
            if (clearDate) {
                clearDate.addEventListener('click', function() {
                    dateFilter.value = '';
                    filterTable();
                });
            }
        }
        
        // 快速筛选按钮
        const viewAll = document.getElementById('viewAll');
        const viewToday = document.getElementById('viewToday');
        const viewMonth = document.getElementById('viewMonth');
        
        if (viewAll) {
            viewAll.addEventListener('click', function() {
                setActiveButton(this);
                dateFilter.value = '';
                filterTable();
            });
        }
        
        if (viewToday) {
            viewToday.addEventListener('click', function() {
                setActiveButton(this);
                const today = new Date().toISOString().split('T')[0];
                dateFilter.value = today;
                filterTable();
            });
        }
        
        if (viewMonth) {
            viewMonth.addEventListener('click', function() {
                setActiveButton(this);
                const date = new Date();
                const firstDay = new Date(date.getFullYear(), date.getMonth(), 1).toISOString().split('T')[0];
                dateFilter.value = '';
                filterTable('month');
            });
        }
        
        // 设置活动按钮
        function setActiveButton(button) {
            const buttons = document.querySelectorAll('.btn-group .btn');
            buttons.forEach(btn => btn.classList.remove('active'));
            button.classList.add('active');
        }
        
        // 表格筛选函数
        function filterTable(monthFilter = null) {
            const searchTerm = searchInput.value.toLowerCase();
            const filterDate = dateFilter.value;
            const rows = document.querySelectorAll('.sale-row');
            
            rows.forEach(function(row) {
                let showRow = true;
                
                // 搜索条件筛选
                if (searchTerm) {
                    const orderId = row.querySelector('h6')?.textContent.toLowerCase() || '';
                    const customer = row.querySelector('td:nth-child(3) .badge')?.textContent.toLowerCase() || '';
                    
                    if (!orderId.includes(searchTerm) && !customer.includes(searchTerm)) {
                        showRow = false;
                    }
                }
                
                // 日期筛选
                if (filterDate && showRow) {
                    const saleDate = row.getAttribute('data-date') || '';
                    if (saleDate !== filterDate) {
                        showRow = false;
                    }
                }
                
                // 月份筛选
                if (monthFilter === 'month' && showRow) {
                    const saleDate = row.getAttribute('data-date') || '';
                    const currentMonth = new Date().getMonth() + 1;
                    const currentYear = new Date().getFullYear();
                    const saleMonth = new Date(saleDate).getMonth() + 1;
                    const saleYear = new Date(saleDate).getFullYear();
                    
                    if (!(saleMonth === currentMonth && saleYear === currentYear)) {
                        showRow = false;
                    }
                }
                
                // 应用显示/隐藏效果
                if (showRow) {
                    row.style.display = '';
                    // 添加淡入效果
                    row.style.opacity = 0;
                    setTimeout(() => {
                        row.style.transition = 'opacity 0.3s ease';
                        row.style.opacity = 1;
                    }, 10);
                } else {
                    row.style.display = 'none';
                }
            });
            const visibleRows = Array.from(rows).filter(row => {
                const style = window.getComputedStyle(row);
                return style.display !== 'none';
            });
            const noResultsRow = document.querySelector('.no-results-row');
            
            if (visibleRows.length === 0 && rows.length > 0) {
                // 如果没有可见行但有数据，显示无结果消息
                if (!noResultsRow) {
                    const tbody = document.querySelector('tbody');
                    const tr = document.createElement('tr');
                    tr.className = 'no-results-row';
                    tr.innerHTML = `
                        <td colspan="6" class="text-center py-4">
                            <div class="d-flex flex-column align-items-center">
                                <i class="bi bi-search text-muted" style="font-size: 2rem;"></i>
                                <p class="mt-2 mb-0">未找到匹配的销售记录</p>
                                <small class="text-muted">尝试使用不同的搜索条件</small>
                            </div>
                        </td>
                    `;
                    tbody.appendChild(tr);
                }
            } else if (noResultsRow) {
                // 如果有可见行，移除无结果消息
                noResultsRow.remove();
            }
        }
    });
</script>
{% endblock %}